package com.example.activiti.config.redis;

import org.springframework.boot.web.servlet.server.Session;

import java.io.*;
import java.util.Base64;

/**
 * @author Mr.yuan
 * @version v1.0
 * @date 2019/11/5 13:34
 **/
public class SerializationUtils {

    public static byte[] serialize(Object o) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outo = new ObjectOutputStream(out);
            outo.writeObject(o);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    public static String serializeToString(Serializable obj) {
        try {
            byte[] value = serialize(obj);
            return Base64.getEncoder().encodeToString(value);
        } catch (Exception e) {
            throw new RuntimeException("serialize session error", e);
        }
    }

    public static Object deserialize(byte[] b) {
        ObjectInputStream oin;
        try {
            oin = new ObjectInputStream(new ByteArrayInputStream(b));
            try {
                return oin.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * string 转session专用
     *
     * @param base64
     * @return
     */
    public static Session deserializeFromString(String base64) {
        try {
            byte[] objectData = Base64.getDecoder().decode(base64);
            return (Session) deserialize(objectData);
        } catch (Exception e) {
            throw new RuntimeException("deserialize session error", e);
        }
    }
}
